package cn.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Desc : TODO
 * ClassName : cn.socket.ServerSocket
 *
 * @author : 林鹏群
 * @date : 2022/12/22 19:54
 */
public class ServerQQ {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8899);
        while (true) {
            Socket clientSocket = serverSocket.accept();


            try (InputStream inputStream = clientSocket.getInputStream();
                 OutputStream outputStream = clientSocket.getOutputStream()) {
                while (true) {
                    // 1. 读取请求并解析.
                    Scanner scanner = new Scanner(inputStream);
                    if (!scanner.hasNext()) {
                        // 读完了, 连接可以断开了.
                        System.out.printf("[%s:%d] 客户端下线!\n", clientSocket.getInetAddress().toString(),
                                clientSocket.getPort());
                        break;
                    }
                    String request = scanner.next();
                    // 2. 根据请求计算响应
                    String response = request;
                    // 3. 把响应写回给客户端
                    //这一步相当于清空outputStream里面的内容
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    //那客户端发来的请求的内容写入到printWriter里面
                    printWriter.println(response);
                    // 刷新缓冲区确保数据确实是通过网卡发送出去了.
                    printWriter.flush();

                    System.out.printf("[%s:%d] req: %s; resp: %s\n", clientSocket.getInetAddress().toString(),
                            clientSocket.getPort(), request, response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 为啥这个地方要关闭 socket ? 而前面的 listenSocket 以及 udp 程序中的 socket 为啥就没 close??
                clientSocket.close();
            }
        }

    }
}
